import React, { useEffect, useState } from "react";
import { MyNavBar } from "../../../components";
import { useNavigate } from "react-router-dom";
import style from "./style.module.scss";
import { useRequest } from "ahooks";
import { generateInvitationCode, getUserInvitationCode } from "../../../api/my";
import { useAppSelector } from "../../../store/hooks";
import QRCode from "qrcode";

const Index: React.FC = () => {
  const navigate = useNavigate();
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);
  const [qrCode, setQrCode] = useState<string>("");
  const invitationCode = useAppSelector(
    (state) => state.user.userInfo.invitationCode
  );
  const { data: inviteCode = invitationCode } = useRequest(async () => {
    if (invitationCode.length > 5) return invitationCode;
    await generateInvitationCode(userId, sessionId);
    const resp = await getUserInvitationCode(userId, sessionId);
    return resp.result;
  });

  useEffect(() => {
    QRCode.toDataURL(inviteCode).then((url: string) => {
      setQrCode(url);
    });
  }, []);

  return (
    <div className={style.wrapper}>
      <div className="navbar">
        <MyNavBar
          title="邀请好友"
          leftArrow
          onClickLeft={() => navigate("/set")}
        ></MyNavBar>
      </div>
      <div className={style.content_wrapper}>
        <div className={style.content}>
          <div className={style.title}>您的邀请码</div>
          <div className={style.inviteCode}>
            {invitationCode === "-1" ? "" : inviteCode}
          </div>
          <div className={style.copyCode}>复制邀请码</div>
          <div className={style.stroke}></div>
          <img className={style.qrCode} src={qrCode} />
          <div className={style.first_text}>要求好友下载APP</div>
          <div className={style.second_text}>
            注册填写下方邀请码&emsp;双方可分别获得300H币
          </div>
          <button className={style.btn_invite}>邀请好友</button>
        </div>
      </div>
    </div>
  );
};

export default Index;
